package cn.sanshuilin.kst.system.provider.write.dao;

import cn.sanshuilin.kst.common.utils.LogPrinter;
import cn.sanshuilin.kst.common.utils.Utility;
import cn.sanshuilin.kst.system.provider.bean.ShareLog;
import org.springframework.stereotype.Repository;

import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;

/**
 * @author greenlee
 * @version v1.0
 * @create 创建时间: 2017-11-29 20:44
 * Copyright 2017  by 三水林科技有限公司
 **/
@Repository
public class ShareLogReq extends AbstractJpaDao<ShareLog> {



    public List<ShareLog> getShareLogsByObjID(int nPageIndex, int nPageSize, String strObjID) {


            String hql = "FROM ShareLog a WHERE a.ShareID= :ObjID ORDER BY a.PubDate";
            Query query = entityManager.createNativeQuery(hql,ShareLog.class);
            query.setParameter("ObjID", strObjID);

            if(nPageIndex!=-1 && nPageSize!=-1){
                query.setFirstResult(nPageIndex * nPageSize);
                query.setMaxResults(nPageSize);
            }
            List<ShareLog> list = query.getResultList();

        return list;
    }


    public long getShareLogsCount(String strKeyword) {
        long count = 0;

            Query query = this.getShareLogsQuery(" COUNT(*) ", strKeyword);
            count = Utility.toSafeLong(query.getSingleResult());
        return count;
    }

    public List<ShareLog> getShareLogs(int nPageIndex, int nPageSize, String strKeyword) {
        List<ShareLog> list = new ArrayList<ShareLog>();
            Query query = getShareLogsQuery("c", strKeyword);
            query.setFirstResult(nPageIndex * nPageSize);
            query.setMaxResults(nPageSize);
            list = query.getResultList();



        return list;
    }

    private Query getShareLogsQuery(String strChange, String strKeyword) {
        String hql = "SELECT " + strChange + " FROM ShareLog c, Share s WHERE c.ShareID=s.ID";
        hql += " ORDER BY c.PubDate DESC ";
        Query query =entityManager.createNativeQuery(hql,ShareLog.class);
        LogPrinter.info("----------------------"+query);
        return query;
    }
}
